package com.usian.ai.common.exception;

import com.usian.ai.common.Result;
import com.usian.ai.common.enums.ResultCodeEnum;
import com.usian.ai.common.exception.exception.PasswordErrorException;
import com.usian.ai.common.exception.exception.UsernameNotExistException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 12 03 14 54
 **/

@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler( RuntimeException.class)
    public Result resultuntimeException(RuntimeException e){
        log.info("RuntimeException:{}",e.getMessage());

        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler( MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.info("methodArgumentNotValidException:{}",e.getMessage());

        BindingResult bindingResult = e.getBindingResult();
        log.info("bindingResult:{}",bindingResult);


        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        log.info("fieldErrors:{}",fieldErrors);
        Map<Object,Object> map = new HashMap<Object,Object>();
        fieldErrors.forEach(error->{
            log.info("error:{}",error);
            String defaultMessage = error.getDefaultMessage();
            log.info("defaultMessage:{}",defaultMessage);
            String field = error.getField();
            log.info("field:{}",field);

            map.put(field,defaultMessage);
        });

   log.info(map.toString());





        e.printStackTrace();
        return Result.fail(map);
    }

    /**
     * 匹配异常类型
     * @param e
     * @return
     */
    @ExceptionHandler( UsernameNotExistException.class)
    public Result usernameNotExistException(UsernameNotExistException e){
        log.info("匹配异常类型usernameNotExistException,code:{},msg:{}",e.getResultCodeEnum().getCode(),e.getResultCodeEnum().getMsg());

        e.printStackTrace();
        return Result.fail(e.getResultCodeEnum());
    }

    @ExceptionHandler( PasswordErrorException.class)
    public Result passwordErrorException(PasswordErrorException e){
        log.info("匹配异常类型passwordErrorException,code:{},msg:{}",e.getResultCodeEnum().getCode(),e.getResultCodeEnum().getMsg());
        e.printStackTrace();
        return Result.fail(e.getResultCodeEnum());
    }
}
